import axios from "axios";
import { useTokenStore } from '../store/tokenStore.js'
import router from "../router/router.js";
import open from './message.js'

const shopAxios = axios.create({
    baseURL: 'http://localhost:8080/'
})

shopAxios.interceptors.request.use(config => {
    const { token } = useTokenStore();
    if (token) {
        config.headers.token = token;
    }
    return config;
});

shopAxios.interceptors.response.use(resp => {

    const { data, errmsg, errno } = resp.data;
    if (errno === 0) {
        if (errmsg != '') {
            open({
                message: errmsg,
                type: 'success',
            })
        }
        return data || true
    }
    if (errmsg != '') {
        open({
            message: errmsg,
            type: 'error',
        })
    }
    if (errno === 2) {
        router.push('/')
    }
    return false;

}, error => {
    if (error.response && error.response.status === 401) {
        open({
            message: '未授权，请重新登录',
            type: 'error',
        });
        router.push('/');
        return Promise.reject(error);
    }
    open({
        message: '请求失败',
        type: 'error',
    });
    return Promise.reject(error);
})

export default shopAxios